package com.lpdemilis.pokermanager;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class RegisterActivity extends Activity implements MyAsyncListener {
	protected CustomHttpClient client;
	protected String SERVER_URL;
	protected String[] countriesKeysStrings;
	protected String[] countriesStrings;

	protected EditText usernameEditText;
	protected EditText passwordEditText;
	protected EditText firstnameEditText;
	protected EditText lastnameEditText;
	protected EditText email1EditText;
	protected EditText email2EditText;
	protected EditText cityEditText;
	protected Spinner countrySpinner;
	protected Button cancelButton;
	protected Button okButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);

		if (Build.MANUFACTURER.equals("unknown")) {
			SERVER_URL = this.getString(R.string.URL_local);
		} else {
			SERVER_URL = this.getString(R.string.URL);
		}
		
		TextView activityTitleTextView = (TextView) findViewById(R.id.activityTitleTextView);
		Typeface titleTypeface = Typeface.createFromAsset(getAssets(),
                "fonts/POKERPN.TTF");        
        activityTitleTextView.setTypeface(titleTypeface);

		usernameEditText = (EditText) findViewById(R.id.usernameEditText);
		passwordEditText = (EditText) findViewById(R.id.passwordEditText);
		firstnameEditText = (EditText) findViewById(R.id.firstnameEditText);
		lastnameEditText = (EditText) findViewById(R.id.lastnameEditText);
		email1EditText = (EditText) findViewById(R.id.email1EditText);
		email2EditText = (EditText) findViewById(R.id.email2EditText);
		cityEditText = (EditText) findViewById(R.id.cityEditText);
		countrySpinner = (Spinner) findViewById(R.id.countrySpinner);
		cancelButton = (Button) findViewById(R.id.cancelButton);
		okButton = (Button) findViewById(R.id.okButton);

		cancelButton.setOnClickListener(cancelButtonClickListener);
		okButton.setOnClickListener(okButtonClickListener);

		try {
			client = new CustomHttpClient(this,
					this.getString(R.string.wait_message), false);
			String action = ActionsEnum.getCountries.toString();
			client.execute(SERVER_URL, action);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public enum ActionsEnum {
		getCountries, registerNewUser, error;
	}

	public enum ErrorsEnum {
		duplicated_username, duplicated_email, auth_emailnoemail, error;
	}

	@Override
	public void executeReturn(String returnValue) {
		String[] returnArray;
		returnArray = returnValue.split("##");

		ActionsEnum action;

		try {
			action = ActionsEnum.valueOf(returnArray[0]);
		} catch (Exception e) {
			action = ActionsEnum.error;
		}

		switch (action) {
		case getCountries:
			getCountriesReurn(returnArray);
			break;
		case registerNewUser:
			registerNewUserReturn(returnArray);
			break;
		case error:
			errorReturn(returnArray);
			break;
		}
	}

	private void registerNewUserReturn(String[] returnArray) {
		if (returnArray.length <= 1) {
			errorReturn(returnArray);
		} else {
			if (returnArray[1].trim().equals("")) {
				AlertDialog alertDialog = new AlertDialog.Builder(
						RegisterActivity.this).create();
				alertDialog.setTitle(R.string.register_email_title);
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.register_email));
				alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
						RegisterActivity.this.getString(android.R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								cancelButton.performClick();
							}
						});

				alertDialog.show();
			} else {
				ErrorsEnum errors;

				try {
					errors = ErrorsEnum.valueOf(returnArray[1]);
				} catch (Exception e) {
					errors = ErrorsEnum.error;
				}

				String errorTitle;
				String errorMessage;

				switch (errors) {
				case auth_emailnoemail:
					errorTitle = this.getString(R.string.error);
					errorMessage = this.getString(R.string.no_email_error);
					break;
				case duplicated_email:
					errorTitle = this.getString(R.string.error);
					errorMessage = this.getString(R.string.duplicated_email_error);
					email1EditText.requestFocus();
					break;
				case duplicated_username:
					errorTitle = this.getString(R.string.error);
					errorMessage = this.getString(R.string.duplicated_username_error);
					usernameEditText.requestFocus();
					break;
				default:
					errorTitle = this.getString(R.string.error);
					errorMessage = this.getString(R.string.error);
					break;
				}

				AlertDialog alertDialog = new AlertDialog.Builder(
						RegisterActivity.this).create();
				alertDialog.setTitle(errorTitle);
				alertDialog.setMessage(errorMessage);
				alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
						RegisterActivity.this.getString(android.R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								return;
							}
						});

				alertDialog.show();
			}
		}
	}

	private void errorReturn(String[] returnArray) {
		AlertDialog alertDialog = new AlertDialog.Builder(RegisterActivity.this)
				.create();
		alertDialog.setTitle(R.string.error);
		alertDialog.setMessage(RegisterActivity.this.getString(R.string.error));
		alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
				RegisterActivity.this.getString(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						return;
					}
				});

		alertDialog.show();
	}

	public void getCountriesReurn(String[] returnArray) {
		ArrayList<String> countries = new ArrayList<String>();

		if (returnArray.length <= 1) {
			// Adicionando string no ArrayList
			countries.add(this.getString(R.string.error));
			countrySpinner.setEnabled(false);
		} else {

			countriesKeysStrings = returnArray[1].split("@@");
			countriesStrings = returnArray[2].split("@@");

			for (int i = 0; i < countriesStrings.length; i++) {
				countries.add(countriesStrings[i]);
			}
		}

		ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_dropdown_item, countries);
		spinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_item);
		countrySpinner.setAdapter(spinnerArrayAdapter);
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
		RegisterActivity.this.startActivity(intent);
		RegisterActivity.this.finish();
	}

	View.OnClickListener cancelButtonClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(RegisterActivity.this,
					LoginActivity.class);
			RegisterActivity.this.startActivity(intent);
			RegisterActivity.this.finish();
		}
	};

	View.OnClickListener okButtonClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					RegisterActivity.this).create();
			alertDialog.setTitle(R.string.error);

			if (usernameEditText.getText().toString().trim().equals("")) {
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.user_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								usernameEditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (passwordEditText.getText().toString().trim().equals("")) {
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.password_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								passwordEditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (firstnameEditText.getText().toString().trim().equals("")) {
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.firstname_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								firstnameEditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (lastnameEditText.getText().toString().trim().equals("")) {
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.lastname_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								lastnameEditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (email1EditText.getText().toString().trim().equals("")) {
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.email1_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								email1EditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (email2EditText.getText().toString().trim().equals("")) {
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.email2_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								email2EditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (!email1EditText.getText().toString().trim()
					.equals(email2EditText.getText().toString().trim())) {
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.email2_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								email2EditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (cityEditText.getText().toString().trim().equals("")) {
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.city_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								cityEditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (countrySpinner.getSelectedItemPosition() == 0) {
				alertDialog.setMessage(RegisterActivity.this
						.getString(R.string.country_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								countrySpinner.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			registerNewUser();
		}
	};

	public void registerNewUser() {
		try {
			client = new CustomHttpClient(this,
					this.getString(R.string.wait_message), true);
			String action = ActionsEnum.registerNewUser.toString();
			String paramName1 = "username";
			String paramValue1 = usernameEditText.getText().toString();
			String paramName2 = "password";
			String paramValue2 = passwordEditText.getText().toString();
			String paramName3 = "firstname";
			String paramValue3 = firstnameEditText.getText().toString();
			String paramName4 = "lastname";
			String paramValue4 = lastnameEditText.getText().toString();
			String paramName5 = "email1";
			String paramValue5 = email1EditText.getText().toString();
			String paramName6 = "email2";
			String paramValue6 = email2EditText.getText().toString();
			String paramName7 = "city";
			String paramValue7 = cityEditText.getText().toString();
			String paramName8 = "countrykey";
			String paramValue8 = countriesKeysStrings[countrySpinner
					.getSelectedItemPosition()];
			String paramName9 = "country";
			String paramValue9 = countriesStrings[countrySpinner
					.getSelectedItemPosition()];
			client.execute(SERVER_URL, action, paramName1, paramValue1,
					paramName2, paramValue2, paramName3, paramValue3,
					paramName4, paramValue4, paramName5, paramValue5,
					paramName6, paramValue6, paramName7, paramValue7,
					paramName8, paramValue8, paramName9, paramValue9);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
